package com.example.an.mymusic;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.List;

/**
 * Created by an on 2017/10/18.
 */
 class ViewContainer{
    public ImageView albumImage;
    public TextView music_title;
    public TextView music_artist;
    public TextView music_duration;
    public ImageButton list_down_button;
    public LinearLayout linearLayout;
}

public class MusicListAdapter extends BaseAdapter {

    private Context context;//上下文对象引用
    private List<Mp3info> mp3infos;//存放Mp3Info引用的集合
    private Mp3info mp3info;//Mp3Info对象引用
    private int pos=-1;
    private ViewContainer vc;


    public MusicListAdapter(Context context,List<Mp3info> mp3Infos) {
        this.context = context;
        this.mp3infos = mp3Infos;
    }

    @Override
    public int getCount() {
        return mp3infos.size();
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        vc=null;
        if (view==null){
            vc=new ViewContainer();
            view= LayoutInflater.from(context).inflate(R.layout.music_list_item_layout,null);
            vc.music_title=(TextView)view.findViewById(R.id.music_title);
            vc.music_artist=(TextView)view.findViewById(R.id.music_Artist);
            vc.music_duration=(TextView)view.findViewById(R.id.music_duration_time);
            vc.list_down_button = (ImageButton)view.findViewById(R.id.list_down_button);
            view.setTag(vc);
        }
        else {
            vc=(ViewContainer)view.getTag();//Adapter 有个getView方法，可以使用setTag把查找的view缓存起来方便多次getTag重用

        }
        mp3info=mp3infos.get(i);
        vc.music_title.setText(mp3info.getTitle());//显示标题
        vc.music_artist.setText(mp3info.getArtist());//显示艺术家
        vc.music_duration.setText(String.valueOf(formatTime(mp3info.getDuration()))); //显示长度
        return view;
    }
    /*将歌曲的时间转换为分秒的制度 */
    public static String formatTime(Long time){
        String min = time / (1000 * 60) + "";
        String sec = time % (1000 * 60) + "";

        if(min.length() < 2)
            min = "0" + min;
        switch (sec.length()){
            case 4:
                sec = "0" + sec;
                break;
            case 3:
                sec = "00" + sec;
                break;
            case 2:
                sec = "000" + sec;
                break;
            case 1:
                sec = "0000" + sec;
                break;
        }
        return min + ":" + sec.trim().substring(0,2);
    }
}
